#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Purpose: Export project object types to an output file
# Created: 01/13/2010
# $Id $
# Copyright (c) 2008,2009 by University College London
# Authors:
#  Didrik Pinte -- <dpinte@dipole-consulting.com>
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with HydroPlatform for details.

import codecs
from itertools import count, chain
import logging
import os
import sets
from sqlalchemy import and_

from hydroplatform.model.export import Exporter, ExportError, ExporterRegistry
from hydroplatform.model import network as nt
from hydroplatform.model import fields as fd
from hydroplatform.model import units

class ExportObjectTypes(Exporter):
    '''
    Exports the object types used in this network to an output file
    
    This is a convenient exporter to analyse the requested types
    
    TODO : export to a python file for reuse
    '''
    _name = "Object types exporter"
    _description  = '''Exports the definition of the object types used in this 
network to a readable file '''
    
    def __init__(self):
        Exporter.__init__(self)
        self.session = None    
        
    def export(self, network, filename, session=None):
        '''
        Export the object types used in this network to a text file
        '''
        ofile = codecs.open(filename, mode="w", encoding="utf8") 
        ntypes = set()
        groups_query = session.query(nt.FieldGroup).order_by(nt.FieldGroup.id).all()
        ofile.write("%s\nGroups :\n" % ("-"*79))
        for group in groups_query:
            ofile.write("%s\n" % str(group))
        
        # get node list for this network ordered by node type
        nodes_query = session.query(nt.Node).filter(\
            nt.Node.networks.any(nt.Network.id == network.id))\
            .order_by(nt.Node.type_id)
        nodes = nodes_query.all()
        for node in nodes:                
            ntypes.add(node.type)
            
        ltypes = set()
        for link in network.links:
            ltypes.add(link.type)
            
        self.export_otypes(ofile, ntypes)
        self.export_otypes(ofile, ltypes)
    
    def export_otypes(self, ofile, otypes):        
        """
        Export the description of every object type in the otypes list 
        to the output file
        """
        attributes = ["id", "name", "description", "size"]
        att_customized = False
            
        for otype in otypes:
            # customize the list of attributes to export depending on the object type
            if att_customized is False:
                if isinstance(otype, nt.NodeType):
                    attributes.extend(["shape", "pen", "brush"])
                elif isinstance(otype, nt.LinkType):
                    attributes.extend(["pen", "style"]) 
                att_customized = True
            ofile.write("%s\n" % (u"#"*80))
            for att in attributes:
                ofile.write(u"%s: %s\n" % (att.title(), getattr(otype, att)))
            ofile.write("--- Fields ---\n")
            for field in otype.fields:
                for att in ["id", "name", "group_id", "attribute_type"]:
                    ofile.write("\t%s : %s\n" % (att.title(), getattr(field, att)))
                ofile.write("\t------\n")
        

REGISTRY = ExporterRegistry()
REGISTRY.register(ExportObjectTypes)
logging.info("Object types exporter extension registered") 
